package ipmi

import (
	"encoding/json"
	"log"
	"net/http"

	ipmi "gitee.com/rogax/ipmi-go"
	"gitee.com/rogax/kagent/pkg/types"
)

// /dev/ipmi0 or /dev/ipmi/0 or /dev/ipmidev/0
type IPMIREQUEST struct {
	DevPath  string `json:"dev_path,omitempty"`
	Hostname string `json:"hostname,omitempty"`
	Port     string `json:"port,omitempty"`
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
}

type IPMI struct {
	Support    bool   `json:"support,omitempty"`
	IP         string `json:"ip,omitempty"`
	SubnetMask string `json:"subnet_mask,omitempty"`
	Gateway    string `json:"gateway,omitempty"`
	MacAddress string `json:"mac_address,omitempty"`
	DevID      uint8  `json:"dev_id,omitempty"`
}

func New(devPath string) *IPMIREQUEST {
	return &IPMIREQUEST{
		DevPath: devPath,
	}
}

func (i *IPMIREQUEST) Get() (string, error) {
	iLan := &IPMI{
		Support:    false,
		IP:         "",
		SubnetMask: "",
		Gateway:    "",
		MacAddress: "",
	}
	iLan.GetIPMILan()
	r := make(map[string]*IPMI)
	r["ipmi"] = iLan
	jsonBytes, err := json.Marshal(r)
	if err != nil {
		log.Println("ipmi数据json序列化失败: ", err)
		return "", err
	}
	return string(jsonBytes), nil

}

func (i *IPMIREQUEST) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	rsp := types.Response{
		Code:    200,
		Message: "success",
		Data:    nil,
	}
	data, err := i.Get()
	if err != nil {
		rsp.Code = 500
		rsp.Message = err.Error()
		w.WriteHeader(http.StatusInternalServerError)
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(rsp)
		return
	}
	rsp.Data = data
	json.NewEncoder(w).Encode(rsp)
}

func (i *IPMI) GetIPMILan() {
	client, err := ipmi.NewOpenClient()
	if err != nil {
		log.Printf("IPMI client creates failed: %s", err)
		i.Support = false
		return
	}

	// Close the session when done.
	defer client.Close()

	// Connect will create an authenticated session for you.
	if err := client.Connect(); err != nil {
		log.Printf("IPMI server connects failed: %s", err)
		i.Support = false
		return
	}

	resID, err := client.GetDeviceID()
	if err != nil {
		log.Printf("Device id gets failed: %s", err)
	}
	i.Support = true
	i.DevID = resID.DeviceID

	res, err := client.GetLanConfig(uint8(0x01))
	// res, err := client.GetLanConfigParams(uint8(0x01), ipmi.LanParamSelector(ipmi.LanParam_IP))
	if err != nil {
		log.Printf("Lan config gets failed: %s", err)
		return
	}
	i.Support = true
	// r := res.ConfigData
	i.IP = res.IP.String()
	i.SubnetMask = res.SubnetMask.String()
	i.Gateway = res.DefaultGatewayIP.String()
	i.MacAddress = res.MAC.String()

	// log.Printf("IPMI LAN: %+v", i)
	// cmd := exec.Command("ipmitool", "-I", "lanplus", "-H", i.IP, "-U", i.Username, "-P", i.Password, "lan", "print")
}
